#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
主题:字典的运算
问题: 怎样在数据字典中执行一些计算操作（比如求最小值、最大值、排序等等）？
提示 : 
"""

# 股票名和价格映射字典
prices = {
    'ACME': 45.23,
    'AAPL': 612.78,
    'IBM': 205.55,
    'HPQ': 37.20,
    'FB': 10.75
}
print(f"{prices = }")

def recipe1():
    '''查找最小和最大股票价格和股票值的代码'''
    # 使用 zip() 函数先将键和值反转过来
    min_price = min(zip(prices.values(), prices.keys()))
    max_price = max(zip(prices.values(), prices.keys()))
    print(f"{min_price = }")
    print(f"{max_price = }")


def recipe2():
    '''排序'''
    prices_sorted = sorted(zip(prices.values(), prices.keys()))
    print(f"{prices_sorted = }")


def recipe3():
    '''zip() 函数创建的是一个只能访问一次的迭代器'''
    prices_and_names = zip(prices.values(), prices.keys())
    print(f"{min(prices_and_names) = }")  # OK
    # print(max(prices_and_names)) # ValueError: max() arg is an empty sequence


def recipe4():
    '''字典对象上执行操作'''
    # 执行普通的数学运算，仅仅作用于键
    print(f"{min(prices) = }")  # Returns 'AAPL'
    print(f"{max(prices) = }")  # Returns 'IBM'

    # 使用字典的 values()方法
    print(f"{min(prices.values()) = }")  # Returns 10.75
    print(f"{max(prices.values()) = }")  # Returns 612.78

    # 提供 key 函数参数来获取最小值或最大值对应的键的信息
    code = min(prices, key=lambda k: prices[k])  # Returns 'FB'
    price = prices[code]
    print(f"{code = }")
    print(f"{price = }")


def recipe5():
    '''如果恰巧最小或最大值有重复的，那么拥有最小或最大键的实体会返回'''
    d = {'AAA': 45.23, 'ZZZ': 45.23}
    min_price = min(zip(d.values(), d.keys()))
    max_price = max(zip(d.values(), d.keys()))
    print(f"{min_price = }")
    print(f"{max_price = }")


def main():
    print('recipe1'.center(20, '*'))
    recipe1()
    print('recipe2'.center(20, '*'))
    recipe2()
    print('recipe3'.center(20, '*'))
    recipe3()
    print('recipe4'.center(20, '*'))
    recipe4()
    print('recipe5'.center(20, '*'))
    recipe5()        


if __name__ == '__main__':
    main()
